<?php

namespace App\Services;

use App\Notifications\SmsCode;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Facades\Notification;

class SmsCodeService
{

    /**
     * session驱动
     *
     * @var Session
     */
    protected $session;

    /**
     * SmsCodeService constructor.
     *
     * @param Session $session
     */
    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    /**
     * 发送短信验证码
     *
     * @param string $mobile 手机号
     * @param int $lifetime 有效期(分钟)
     *
     * @return boolean
     */
    public function send($mobile, $lifetime = 15)
    {
        if (config('app.debug')) {
            $code = substr($mobile, 5);

        } else {
            $code = rand(100100, 999099);

            Notification::route('sms', $mobile)
                ->notify(new SmsCode($code));
        }

        // 写入session
        $this->session->put(static::getKey($mobile), [
            'code' => $code,
            'expire' => time() + $lifetime * 60
        ]);

        return true;
    }

    /**
     * 检查验证码是否正确
     *
     * @param $mobile
     * @param $input
     *
     * @return bool
     */
    public function check($mobile, $input)
    {

        $session = $this->session->get(static::getKey($mobile));


        if (array_has($session, 'expire')) {

            if ($session['expire'] >= time()) {

                return (string)$input === (string)array_get($session, 'code');
            }

            // 已过期
            $this->forget($mobile);
        }

        return false;
    }

    /**
     * 删除验证码存储
     *
     * @param $mobile
     */
    public function forget($mobile)
    {
        $this->session->forget(static::getKey($mobile));
    }

    /**
     * 返回存储在缓存中的key
     *
     * @param $mobile
     *
     * @return string
     */
    protected static function getKey($mobile)
    {
        return 'sms_code.' . $mobile;
    }
}